import dotenv from 'dotenv';
import { dbLogger } from '../logger';
import { useConfig } from '../config';
import { Sequelize } from 'sequelize-typescript';
import path from 'path';
import Redis from 'ioredis';

dotenv.config();
const dbconnect = () => {
  const sequelize = new Sequelize(
    useConfig().db.db_database,
    useConfig().db.db_user,
    useConfig().db.db_pass,
    {
      host: useConfig().db.db_host,
      // 选择一种支持的数据库:
      // 'mysql', 'mariadb', 'postgres', 'mssql', 'sqlite', 'snowflake', 'db2' or 'ibmi'
      dialect: 'mysql',
      logging: (msg) => dbLogger.info(msg),
      models: [path.join(__dirname, '..', 'model/**/*.{ts,js}')],
      define: {
        freezeTableName: true,
        timestamps: true, // 是否时间戳
        createdAt: 'created_at',
        updatedAt: 'updated_at',
      },
      pool: {
        max: 10,
        min: 0,
        idle: 10000,
        acquire: 30000,
      },
      timezone: '+08:00',
      dialectOptions: {
        dateStrings: true,
        typeCast: true,
      },
    },
  );

  return sequelize;
};
(async () => {
  try {
    const sequelize = dbconnect();
    await sequelize.authenticate();
    const redis = new Redis(parseInt(useConfig().redis.port), useConfig().redis.host, {
      password: useConfig().redis.password,
    }); // 初始化Redis客户端
    redis.auth(useConfig().redis.password, () => {
      console.log('redis认证成功');
    });
    redis.ping(() => {
      console.log('redis连接成功');
    });
    global.redis = redis;
    console.log('Connection has been established successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
})();
